package concurrent.juc.countdownlatch;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * @author: 黄嘉振
 * @create: 2023/6/15 17:38
 * @description:
 **/
public class CountDownLatchDemo {
    private volatile static CountDownLatch countDownLatch = new CountDownLatch(3);

    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 3; i++) {
            new Thread(new CountDownLatchTask(countDownLatch, i)).start();
        }
        countDownLatch.await();
        System.out.println("子任务全部完成！");
    }
}

class CountDownLatchTask implements Runnable {
    private int i;
    private CountDownLatch countDownLatch;

    public CountDownLatchTask(CountDownLatch countDownLatch, int i) {
        this.countDownLatch = countDownLatch;
        this.i = i;
    }

    @Override
    public void run() {
        try {
            Random random = new Random();
            int sleepTime = random.nextInt(1000);
            TimeUnit.MILLISECONDS.sleep(sleepTime);
            // 异常也算是任务完成
            if (i == 1) {
                System.out.println(Thread.currentThread().getName() + "子任务执行异常！");
                throw new RuntimeException();
            }
            System.out.println(Thread.currentThread().getName() + "子任务执行正常！sleep time=" + sleepTime);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            countDownLatch.countDown();
        }
    }
}
